<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    /**
     * The demos backend service.
     *
     * @package    applications.services
     * @subpackage backend
     *
     * @author NairuS
     * @version 1.2 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     */
    class UsersBackendService extends ServicesAdmin
    {
        /**
         * Create an instance of UsersBackendService
         *
         * @param string $file initialize an other mysql configuration.
         */
        public function __construct( $file = null )
        {
            parent::__construct($file);
            $this->table = '`kp_users`';
        }

        /**
         * Deletes an object of the model with the id passed-in.
         *
         * @param mixed $id integer or string identifier of the object.
         * @return boolean  True if the object has been deleted, false otherwise.
         */
        public function delete( $id )
        {
            $query = "DELETE FROM " . $this->table . " WHERE " . $this->table . ".`id` = '" . $this->sanitize( $id ) . "';" ;
            return $this->getResult( $query ) ;
        }

        /**
         * Return the UserVO for the id passed-in.
         *
         * @param  mixed  $id integer or string identifier of the object.
         * @return UserVO     if query succeed, false otherwise.
         */
        public function find( $id )
        {
            $query  = "SELECT * FROM " . $this->table . " WHERE " . $this->table . ".`id` = '" . $this->sanitize( $id ) . "'" ;
            $result = $this->getResult( $query ) ;

            if( mysql_num_rows( $result ) )
            {
                $vo = $this->getVO( mysql_fetch_array( $result ) ) ;

                // remove password from the vo.
                $vo->password = null;

                return $vo;
            }
            else
            {
                return false;
            }
        }

        /**
         * Return an array of UserVO.
         *
         * @param  array  $conditions     defines the where conditions of the query.
         * @param  array  $orders         defines the orderBy conditions of the query.
         * @param  string $orderDirection defines the orderBy direction of the query.
         * @return array                  of RoleVO.
         */
        public function findAll( $conditions = array(), $orders = array(), $orderDirection = ServicesMysql::ASC )
        {
            $where   = empty( $conditions ) ? null : $this->buildWhere( $conditions ) ;
            $orderBy = empty( $orders )     ? null : $this->buildOrderBy( $orders, $orderDirection );
            $query   = "SELECT * FROM " . $this->table . $where . $orderBy . ";" ;
            $result  = $this->getResult( $query ) ;

             $stack = array() ;
            if( mysql_num_rows($result) > 0 )
            {
                while( $row = mysql_fetch_array( $result ) )
                {
                    array_push( $stack, $this->getVO( $row ) ) ;
                }
            }
            return $stack ;
        }

        /**
         * Insert an user in the database.
         *
         * @param  array $datas
         * @return mixed last inserted id if the object has been inserted, ErrorsModelVO otherwise.
         */
        public function insert( $datas )
        {
            $model  = new UserModel( $this->getVO( $datas ) );
            $sql    = "INSERT INTO " . $this->table . " (`block`, `email`, `firstName`, `lastName`, `password`, `roleID`, `userName`) VALUES('{block}', '{email}', '{firstName}', '{lastName}', MD5('{password}'), '{roleID}', '{userName}');";
            $result = $this->validate( $model, $sql );
            if( $result === true )
            {
                return $this->connect->getLastID();
            }
            return $result;
        }

        /**
         * Try to login an user
         *
         * @param  string $userName
         * @param  string $password
         *
         * @return boolean true if the authentication succeed, false otherwise.
         */
        public function login( $userName, $password )
        {
            $sql    = 'SELECT * FROM ' . $this->table . ' WHERE ' . $this->table . '.`userName` = \'' . $this->sanitize( $userName ) . '\' AND ' . $this->table . '.`password` = \'' . md5( $password ) . '\';';
            $result = $this->getResult( $sql ) ;

            if( mysql_num_rows( $result ) > 0 )
            {
                // TODO check if the user is not blocked....
                return true;
            }
            else
            {
                return false;
            }
        }

        /**
         * Update user's datas in the db.
         *
         * @param  array $datas
         *
         * @return mixed true if the update succeed, ErrorsModelVO otherwise.
         */
        public function update( $datas )
        {
            $model = new UserModel( $this->getVO( $datas ) );
            $sql   = "UPDATE " . $this->table . " SET
                        `block` = '{block}',
                        `email` = '{email}',
                        `firstName` = '{firstName}',
                        `lastName` = '{lastName}',
                        `roleID` = '{roleID}',
                        `userName` = '{userName}'";

            // if we want to change the password
            if( $model->getVO()->password != '' )
            {
                $sql .= ",`password` = MD5('{password}')";
            }
            $sql .= "WHERE `id` = " . $this->sanitize( $model->vo->id ) . ";";
            return $this->validate($model, $sql);
        }

        /**
         * Returns the UserVO of a result query row.
         *
         * @param  array  $row A row datas from the database to format in UserVO.
         * @return UserVO      of a result query row.
         */
        protected function getVO( array $row )
        {
            $vo = new UserVO( $row );
            $vo->block = $this->isTrue( isset( $row["block"] ) ? $row["block"] : false ) ;
            return $vo;
        }
    }
?>